package ServiceProvider;

import java.util.HashSet;
import java.util.List;

import DataCenter.ConfigAccessor;

public class SubCmdOperator {
	
	private ConfigAccessor configAccessor;
	private SubscriptionCenter subscriptionCenter;
	
	private HashSet<String> subscribedTopicNameSet;
	
	public SubCmdOperator() {
		this.configAccessor = ConfigAccessor.sharedInstance();
		this.subscriptionCenter = SubscriptionCenter.sharedInstance();
		
		this.subscribedTopicNameSet = configAccessor.getSubscribedTopicNamesSet();
	}

	
	/*
	 * operate topics
	 */
	
	public void operateTheTopics(String operation, List<String> topics) {
		
		subscriptionCenter.beginUpdate();
		
		if (operation.equals("Subscribe"))
			subscribeTheTopics(topics);
		else if (operation.equals("Cancel"))
			cancelSubscribeTheTopics(topics);
		
		subscriptionCenter.endUpdate();
		
		configAccessor.printSubscribedTopicNames();
	}
	
	private void subscribeTheTopics(List<String> topics) {
		
		for (String topic : topics) {
			if (this.subscribedTopicNameSet.contains(topic))
				System.out.println("Already subscribed: " + topic);
			else
				this.subscriptionCenter.listenNewTopic(topic);
		}
	}
	
	private void cancelSubscribeTheTopics(List<String> topics) {
		
		for (String topic : topics) {
			if (this.subscribedTopicNameSet.contains(topic))
				this.subscriptionCenter.unlistenAlreadyListenedTopic(topic);
			else
				System.out.println("Hasn't subscribed: " + topic);
		}
	}
	
}
